﻿using Microsoft.Playwright;
using System;
using System.Threading.Tasks;

namespace playwright
{
    class Program
    {
        static async Task Main(string[] args)
        {
            //创建playwright
            using var playwright = await Playwright.CreateAsync();
            //创建并启动浏览器模拟器
            await using var browser = await playwright.Chromium.LaunchAsync();
            //获取上下文对象，并设置录屏保持路径
            await using var context = await browser.NewContextAsync(new BrowserNewContextOptions() { 
               RecordVideoDir="videos"
            });
            //设置追踪记录
            await context.Tracing.StartAsync(new TracingStartOptions()
            {
                Screenshots=true,
                Snapshots=true
            });
            //上下文创建页面
            var page = await context.NewPageAsync();
            //跳转到目录
            await page.GotoAsync("http://47.95.14.161:1000/login.html");

            //延时1秒后截图
            await Task.Delay(1000).ContinueWith(async t =>
              {
                  await page.ScreenshotAsync(new PageScreenshotOptions { Path = "screenshot1.png" });
              });
            //输入账号密码
            await page.FillAsync("body>form>div:nth-child(2)>input", "admin");
            await page.FillAsync("body>form>div:nth-child(3)>input", "admin");
            //获取登录按钮
            var button=await page.QuerySelectorAsync("body>form>div:nth-child(5)>button");
            //点击登录按钮
            await button.ClickAsync();
            //上面操作也可以改为一条命令
            /* await page.ClickAsync("body>form>div:nth-child(5)>button");*/
           //保存追踪记录到压缩包
            await context.Tracing.StopAsync(new TracingStopOptions
            {
                Path=DateTime.Now.ToString("yyMMddHHmmss")+"shiyi.zip"
             });
            //关闭上下文，结束录屏
            await context.CloseAsync();
        }
    }
}
